<?php
namespace backend\controllers;
use backend\models\Category;
use Yii;
use yii\web\Controller;

class CategoryController extends Controller{

    public function actionAdd(){
        $model = new Category();
        $list = $model->getOptions();
        if(Yii::$app->request->isPost){
           $data = Yii::$app->request->post();
            if($model->load($data) && $model->validate()){
                $data['Category']['create_time'] = time();
                if($model->addCate($data)){
                   Yii::$app->session->setFlash('info', '添加菜单成功');
                }
            }
        }
        return $this->render('cate_add', [
            'model' => $model,
            'list'  => $list,
        ]);
    }

    public function actionList(){
        $model = new Category();
        $cates = $model->getTreeList();
        return $this->render('cate_list', ['model' => $model, 'cates' => $cates]);
    }

    public function actionAjax_getcate(){
        if(Yii::$app->request->isAjax){
            $cateid = Yii::$app->request->get('cateid');
            $model = new Category();
            $cates = $model->find()->where('parentid = :cateid', [':cateid' => $cateid])->asArray()->all();
            if(!$cates){
                echo json_encode(['status' => 1, 'data' => $cates, 'msg' => '数据为空']);
            }
            echo json_encode(['status' => 0, 'data' => $cates, 'msg' => 'ok']);
        }
    }

    public function actionMod(){
        $model = new Category();
        $cateid = Yii::$app->request->get('cateid');
        $model = $model->find()->where('cateid = :id ', [':id' => $cateid])->one();
        $list = $model->getOptions();
        if(Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            if($model->load($data) && $model->save()){
                Yii::$app->session->setFlash('info', '修改数据成功');
            }
        }
        return $this->render('cate_add', ['model' => $model, 'list' => $list]);
    }

    public function actionDel(){
        $model = new Category();
        try{
            $cateid = Yii::$app->request->get('cateid');
            if(empty($cateid)){
                throw new \Exception('参数有误');
            }
            $data = $model->find()->where('parentid =:id', [':id' => $cateid])->one();
            if($data){
                throw new \Exception('该分类下有子类,不允许删除');
            }
            if(!Category::deleteAll('cateid = :id', [':id' => $cateid])){
                Yii::$app->session->setFlash('info', '删除失败');
            }
        }catch (\Exception $e){
            Yii::$app->session->setFlash('info', $e->getMessage());
        }
        return $this->redirect(['category/list']);

    }
}